package netty.kakai.com.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class DiscardServer {

    private int port;

    public DiscardServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        // 我们在这里使用了两个NioEventLoopGroup来处理I/O操作 : 1. boss，接收链接请求
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 2. worker，在boss接受了请求之后向worker注册。具体使用多少线程取决于EventLoopGroup的实现
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // ServerBootstrap是建立服务器的帮助类，也可以直接使用Channel来建立服务器
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    // 使用NioServerSocketChannel来初始新的Channel来接收请求
                    .channel(NioServerSocketChannel.class)
                    // 指定的handler经常被新Channel评估；ChannelInitializer是帮助用户配置新Channel的特定handler
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new DiscardServerHandler());
                        }
                    })
                    // 我们在这里是实现一个TCP/IP服务器，我们使用了tcpNoDelay和keepAlive，至于其它的选项，请到ChannelOption和ChannelConfig里面去查找
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // option是给接受请求的NioServerSocketChannel的，childOption是给父ServerChannel接受的Channel，在这里是NioServerSocketChannel
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            // 绑定端口，启动服务器
            ChannelFuture f = b.bind(port).sync();

            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8080;
        }
        new DiscardServer(port).run();
    }

}
